from account.account_service import AccountService, accounts_write_lock
from threading import Timer
from common.logger import logger
import common.http as http
import json
from database.park_token_table import ParkTokenTable
import spider_config

class YunAccountService(AccountService):
    def __init__(self, interval: int) -> None:
        super().__init__()
        self.__interval = interval

    def active(self):
        if not self._is_active:
            self.fetch()
            self._is_active = True

    def fetch(self):
        with accounts_write_lock:
            with ParkTokenTable() as db:
                data = db.query_all(spider_config.yun_park_id, 500)
                self._clear()
                for item in data:
                    self._accounts.append(json.loads(item.data))
            logger.success(f"补充智慧停车云平台账号完成，剩余账号数量: {len(self._accounts)}")
            self.timer = Timer(self.__interval, self.fetch, ()).start()
            
    def take(self):
        with accounts_write_lock:
            if not self._accounts:
                logger.error("智慧停车账号不足，尝试重新获取")
                self.fetch()
            return super().take()
